package org.zjt.platform.springbootreactivedemo.service.impl;

import org.zjt.platform.springbootreactivedemo.entity.Person;
import org.zjt.platform.springbootreactivedemo.repository.PersonRepository;
import org.zjt.platform.springbootreactivedemo.service.PersonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.NumberUtils;
import org.springframework.web.reactive.function.server.ServerRequest;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author <a href="juntao.zhang@qq.com">juntao.zhang</a>
 * @Description:
 * @Package org.zjt.platform.springbootreactivedemo.service.impl
 * @date 2018/3/15 10:49
 * @see
 */
@Service
@Slf4j
public class PersonServiceImpl implements PersonService {

    @Autowired
    private PersonRepository personRepository;


    @Override
    public Mono<Person> getPerson(ServerRequest request) {
        return Mono.justOrEmpty(personRepository.getPerson(NumberUtils.parseNumber(request.pathVariable("id"), Long.class)));
    }

    @Override
    public Mono<Boolean> savePerson(ServerRequest request) {
        return request.bodyToMono(Person.class).map(person -> {
            try {
                personRepository.savePerson(person);
                return true;
            }catch (Exception e){
                log.error("保存person异常",e);
            }
            return false;
        });
    }

    @Override
    public Mono<Void> deletePerson(ServerRequest request) {
        return Mono.create(voidMonoSink -> {
            personRepository.deletePerson(NumberUtils.parseNumber(request.pathVariable("id"), Long.class));
            voidMonoSink.success();
        });
    }

    @Override
    public Flux<Person> getAllPerson() {
        return Flux.fromStream(personRepository.getAllPerson().stream());
    }
}
